package com.rran.study.designpattern.behavioral.chain.repository;

import com.google.common.collect.Lists;
import com.rran.study.designpattern.behavioral.chain.chain.spring.ChainSpringHandler;
import com.rran.study.designpattern.behavioral.chain.enums.ChainAction;
import com.rran.study.designpattern.behavioral.chain.enums.ChainType;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author yy
 * @Type ChainHandlerRepository.java
 * @Desc
 * @date 2020/7/20 15:07
 */
public class ChainHandlerRepository {

    /**
     * 存放每个责任链第一个handler
     */
    public static Map<String, ChainSpringHandler> headHandlerMap = new ConcurrentHashMap<>();
    private static Map<String, List<ChainSpringHandler>> handlerChainMap = new ConcurrentHashMap<>();
    private static Map<ChainType, List<ChainAction>> handleActionMap = new ConcurrentHashMap<>();

    public static void storeHeadHandler( ChainType chainType, ChainSpringHandler handler) {
        headHandlerMap.put(generateKey(chainType), handler);
    }

    public static void storeChain(ChainType chainType, ChainSpringHandler handler) {
        String key = generateKey(chainType);
        if (handlerChainMap.containsKey(key)) {
            handlerChainMap.get(key).add(handler);
        } else {
            handlerChainMap.put(key, Lists.newArrayList(handler));
        }
    }

    public static void storeAction(ChainType chainType, ChainAction action) {
        if (handleActionMap.containsKey(chainType)) {
            List<ChainAction> chainActions = handleActionMap.get(chainType);
            if (!chainActions.contains(action)) {
                handleActionMap.get(chainType).add(action);
            }
        } else {
            handleActionMap.put(chainType, Lists.newArrayList(action));
        }
    }

    public static ChainSpringHandler getChainHeadHandler(ChainType chainType) {
        return headHandlerMap.get(generateKey(chainType));
    }

    public static List<ChainSpringHandler> getHandlerChain(ChainType chainType) {
        return handlerChainMap.get(generateKey(chainType));
    }

    public static List<ChainAction> getHandlerActions(ChainType chainType) {
        return handleActionMap.get(chainType);
    }

    private static String generateKey(ChainType chainType) {
        return chainType.name();
    }


}
